package algorithm;

/**
 * v155. 最小栈
 */
public class T00155 {
    /**
     * ["MinStack","push","push","push","top","pop","getMin","pop","getMin","pop","push","top","getMin","push","top","getMin","pop","getMin"]
     * [[],[2147483646],[2147483646],[2147483647],[],[],[],[],[],[],[2147483647],[],[],[-2147483648],[],[],[],[]]
     * @param args
     */
    public static void main(String[] args) {
        MinStack minStack = new MinStack();
        minStack.push(2147483646);
        minStack.push(2147483646);
        minStack.push(2147483647);
        System.out.println(minStack.top());    //  --> 返回 0.
        minStack.pop();
        System.out.println(minStack.getMin()); //  --> 返回 -3.
        minStack.pop();
        System.out.println(minStack.getMin()); //  --> 返回 -2.
        minStack.pop();

        minStack.push(2147483647);
        System.out.println(minStack.top());
        System.out.println(minStack.getMin());
        minStack.push(-2147483648);
        System.out.println(minStack.top());
        System.out.println(minStack.getMin());
        minStack.pop();
        System.out.println(minStack.getMin());
    }

private static class MinStack {

    private StackNode head;

    /** initialize your data structure here. */
    public MinStack() {
    }

    public void push(int x) {
        if(head == null)
            head = new StackNode(x, x);
        else
            head = new StackNode(x, x < head.min ? x : head.min, head);
    }

    public void pop() {
        head = head.next;
    }

    public int top() {
        return head.val;
    }

    public int getMin() {
        return head.min;
    }

    private static class StackNode {
        int val;
        int min;
        StackNode next;

        public StackNode(int val, int min) {
            this.val = val;
            this.min = min;
        }

        public StackNode(int val, int min, StackNode next) {
            this.val = val;
            this.min = min;
            this.next = next;
        }
    }
}
}